<template>
	<baseDialog ref="dialogRef" title="导入数据表" width="960px" @confirm="handleSubmit" @close="handleClose">
		<div>
			<el-card class="layout-search-card mb-4" shadow="never" :body-style="{ paddingBottom: '0' }">
				<el-form :model="state.queryParams" ref="queryForm" :inline="true">
					<el-form-item label="表名：">
						<el-input v-model="state.queryParams.name" placeholder="请输入表名" class="w-[200px]"> </el-input>
					</el-form-item>
					<el-form-item>
						<el-button-group>
							<el-button type="primary" icon="ele-Search" @click="searchTable"> 查询 </el-button>
							<el-button icon="ele-Refresh" @click="resetQuery" class="ml15"> 重置 </el-button>
						</el-button-group>
					</el-form-item>
				</el-form>
			</el-card>
			<el-card class="layout-table-card" shadow="never">
				<el-table ref="tableRef" :data="state.tableList" highlight-current-row v-loading="state.loading" @selection-change="handleSelectionChange">
					<el-table-column type="selection" width="55" />
					<el-table-column prop="Name" label="表名称" show-overflow-tooltip></el-table-column>
					<el-table-column prop="Comment" label="表注释" show-overflow-tooltip></el-table-column>
					<el-table-column prop="Create_time" label="创建时间" show-overflow-tooltip></el-table-column>
				</el-table>
				<div class="flex justify-end mt-4">
					<pagination v-model="state" @tableChange="getTableList" />
				</div>
			</el-card>
		</div>
	</baseDialog>
</template>

<script setup lang="ts" name="codeImport">
import { ref, reactive, onMounted } from 'vue';
import { getAllTableList } from '/@/api/crud/table';
import { messageError, messageSuccess } from '/@/utils/message';
import { codeImport } from '/@/api/crud/code';
import { usePage } from '/@/hooks/usePage';

const dialogRef = ref(null);

const tableRef = ref(null);

const selectDataList = reactive({
	data: [],
});

const emit = defineEmits(['submit', 'close']);

// 定义列表
const state = reactive<TableDataState>({
	loading: false,
	tableList: [],
	queryParams: {
		name: '',
	},
	tableParams: {
		page_num: 1,
		page_limit: 15,
		page_total: 0 as any,
	},
});

const { getTableList, searchTable, resetQuery } = usePage({ tableData: state, apiData: getAllTableList });

const handleSelectionChange = (val) => {
	selectDataList.data = [];
	val.forEach((e) => {
		selectDataList.data.push({ name: e.Name });
	});
};

const handleSubmit = async () => {
	if(!selectDataList.data.length) {
		messageError('请选择数据表');
		return;
	}
	// 导入数据表
	await codeImport({tables:selectDataList.data});
	messageSuccess('导入成功');
	dialogRef.value?.close();
	emit('submit');
};

const handleClose = () => {
	emit('close');
};

const open = () => {
	// 重置选中数据
    if(selectDataList.data.length) {
		selectDataList.data = [];
		tableRef.value.clearSelection();
	}
	dialogRef.value?.open();
};

defineExpose({
	open,
});

onMounted(() => {
	getTableList();
});
</script>
